'use strict';

const Controller = require('../core/base_controller');
var OAuth = require('co-wechat-oauth');
var client = new OAuth('wxe271fc6e4cef04a4', '15b1d92f7299a82655d11db4b76338ee');
//测试用
// var client = new OAuth('wx9f2c98afbbbbcc03', '0c0a91170dabd08566aafb2f646a28fa');

class AuthController extends Controller {
  async index() {
    const {ctx,app} = this;
    let query = ctx.query;
    let redirect = query.redirect;

    redirect =  encodeURIComponent(redirect)

    let code = query.code;

    if (code == undefined){
        const url = client.getAuthorizeURL('http://jyx.7chejian.com/auth?redirect='+redirect, '', 'snsapi_userinfo');
        // const url = client.getAuthorizeURL('http://lmm.vipgz1.idcfengye.com/auth?redirect='+redirect, '', 'snsapi_userinfo');
        console.log(url);
        await ctx.redirect(url);
    }else{
        try {
            var token = await client.getAccessToken(code);
            var accessToken = token.data.access_token;
            var openid = token.data.openid;

            let newredirect =  decodeURIComponent(redirect);
            let newarray = newredirect.split('#');
            let frontUrlArray = newarray[0].split("?");
            let newUrl = "";
            newUrl = `${frontUrlArray[0]}?openid=${openid}#${newarray[1]}`;
            if (frontUrlArray.length > 1){
                newUrl = `${frontUrlArray[0]}?${frontUrlArray[1]}&openid=${openid}#${newarray[1]}`;
            }
            await ctx.redirect(newUrl);
        } catch (error) {
            const url = client.getAuthorizeURL('http://jyx.7chejian.com/auth', '', 'snsapi_userinfo');
            await ctx.redirect(url);
        }
    }
  }
}

module.exports = AuthController;
